// register.js
document.addEventListener('DOMContentLoaded', function() {
    const registerForm = document.getElementById('registerForm');

    registerForm.addEventListener('submit', async function(e) {
        e.preventDefault();

        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value.trim();
        const confirmPassword = document.getElementById('confirmPassword').value.trim();

        // 前端基本验证
        if (!username || !password || !confirmPassword) {
            alert('所有字段都是必填的');
            return;
        }

        if (password !== confirmPassword) {
            alert('两次输入的密码不一致');
            return;
        }

        // 构造请求数据
        const requestData = {
            username: username,
            password: password
        };

        try {
            // 发送注册请求
            const response = await fetch('/api/register', { // 直接访问FastAPI服务
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            });

            // 添加网络错误检测
            if (!response.ok) {
                throw new Error(`HTTP错误: ${response.status}`);
            }

            const data = await response.json();

            if (data.user_id) {
                alert('注册成功！');
                window.location.href = 'login.html';
            } else {
                alert('注册失败：' + (data.detail || data.message || '未知错误'));
            }
        } catch (error) {
            console.error('注册错误:', error);

            // 区分不同类型的错误
            if (error instanceof TypeError && error.message.includes('NetworkError')) {
                alert('网络错误：无法连接到服务器，请确保服务正在运行');
            } else if (error.message.startsWith('HTTP错误:')) {
                alert(`服务器返回错误: ${error.message}`);
            } else {
                alert('注册过程中出现错误，请稍后重试\n详细错误：' + error.message);
            }
        }
    });

    // 登录链接跳转
    document.getElementById('loginLink').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'login.html';
    });
});
